<template>
  <zeda-dialog
    v-model="visible"
    title="碳中和申报"
    width="1000px"
    :before-close="handleClose"
  >
    <el-form ref="form" :model="model" :rules="rules" label-width="0">
      <div v-for="(item, index) in model.energyCarbonNeutralPlans" :key="index">
        <Title :name="item.planName" :line="false">
          <el-table
            :ref="'table' + index"
            :data="item.children"
            style="width: 100%"
            border
            max-height="300"
            @selection-change="(value) => handleSelectionChange(value, item)"
          >
            <el-table-column type="selection" width="55" align="center">
            </el-table-column>
            <el-table-column align="center">
              <template slot="header">
                <span>名称</span>
              </template>
              <template slot-scope="scope">
                {{ scope.row.energyName }}
              </template>
            </el-table-column>
            <el-table-column align="center">
              <template slot="header">
                <span>单价</span>
                <i style="color: #f56c6c">*</i>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'energyCarbonNeutralPlans[' +
                    index +
                    '].children[' +
                    scope.$index +
                    '].measurePrice'
                  "
                  :rules="rules.measurePrice"
                >
                  <el-input
                    type="text"
                    v-model="scope.row.measurePrice"
                    autocomplete="off"
                    :disabled="!scope.row.checked"
                    @input="
                      (value) =>
                        keyFixAmount(value, scope.row, 'measurePrice', true)
                    "
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center">
              <template slot="header">
                <span>数量</span>
                <i style="color: #f56c6c">*</i>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'energyCarbonNeutralPlans[' +
                    index +
                    '].children[' +
                    scope.$index +
                    '].measureNum'
                  "
                  :rules="rules.measureNum"
                >
                  <el-input-number
                    v-model="scope.row.measureNum"
                    :disabled="!scope.row.checked"
                    :min="1"
                    :max="9999999"
                    @change="(value) => changesuggestDeal(value, scope.row)"
                    @input="(value) => inputsuggestDeal(value, scope.row)"
                  ></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center">
              <template slot="header">
                <span>总价</span>
              </template>
              <template slot-scope="scope">
                {{ scope.row.measureNum * scope.row.measurePrice }}
                <span class="suggest" v-if="scope.row.suggest">(模型建议)</span>
              </template>
            </el-table-column>
          </el-table>
        </Title>
      </div>
      <el-form-item prop="instructionsResult">
        <el-input
          type="textarea"
          v-model="model.instructionsResult"
          placeholder="请输入分析意见"
        ></el-input>
      </el-form-item>
    </el-form>
    <form-button
      slot="footer"
      :loading="loading"
      @cancel="handleClose"
      @submit="submit"
    >
    </form-button>
  </zeda-dialog>
</template>
<script>
import { neutralConfirm } from "@/api/carbonNeutral/government";
import FormButton from "@/components/FormButton";
import { replaceDigit } from "@/utils/index";
export default {
  components: {
    FormButton,
  },
  props: {
    id: { type: [Number, String], default: "" },
    visible: { type: Boolean, default: false },
    data: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      loading: false,
      model: {
        id: null,
        energyCarbonNeutralPlans: [],
        instructionsResult: "",
      },
      rules: {
        measurePrice: [
          {
            required: true,
            trigger: ["change", "blur"],
            message: "请输入单价",
          },
        ],
        measureNum: [
          {
            required: true,
            message: "请输入数量",
            trigger: ["change", "blur"],
          },
        ],
        instructionsResult: [
          {
            required: true,
            message: "请输入分析意见",
          },
        ],
      },
    };
  },
  watch: {
    visible(value) {
      if (value) {
        this.model.id = this.data.id;
        this.model.energyCarbonNeutralPlans = JSON.parse(
          JSON.stringify(this.data.plans)
        );
        this.fakesuggest();
      } else {
        this.model.energyCarbonNeutralPlans = [];
      }
    },
  },
  methods: {
    /* 默认建议---假数据，后期后端传 */
    fakesuggest() {
      let obj1 = this.model.energyCarbonNeutralPlans[0];
      let obj = obj1.children[0];
      obj.measurePrice = 10;
      obj.measureNum = 2;
      obj.suggest = true;
      // console.log([obj], obj1);
      this.toggleSelection([obj]);
    },
    /* 默认勾选操作-后期结合后端建议数据可用 */
    toggleSelection(rows) {
      if (rows) {
        let that = this;
        rows.forEach((row) => {
          that.$nextTick(() => {
            // console.log(that.$refs.table0[0]);
            that.$refs.table0[0].toggleRowSelection(row);
          });
        });
      }
    },
    keyFixAmount(value, item, key, flage) {
      if (flage) {
        item.suggest = undefined; // 建议取消
      }
      item[key] = replaceDigit(value, 2);
    },
    changesuggestDeal(value, row) {
      row.suggest = undefined; // 建议取消
    },
    inputsuggestDeal(value, row) {},
    // 多选框选中数据
    handleSelectionChange(selection, item) {
      item.children.forEach((it) => {
        it.checked = false;
        return it;
      });
      selection.forEach((item) => {
        item.checked = true;
        return item;
      });
    },
    submit() {
      let list = [];
      this.model.energyCarbonNeutralPlans.map((item) => {
        item.children.map((it) => {
          if (it.checked === true) {
            list.push(it);
          }
        });
        return item;
      });
      if (list.length <= 0) {
        this.$message.warning("最少选择一条修改");
        return false;
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = {
            id: this.model.id,
            energyCarbonNeutralPlans: list,
            instructionsResult: this.model.instructionsResult,
          };
          this.loading = true;
          neutralConfirm(data)
            .then((res) => {
              this.loading = false;
              if (res.code === 700) {
                this.$message.warning(res.msg);
                return false;
              }
              this.$message.success("操作成功");
              this.handleClose(true);
            })
            .catch(() => {
              this.loading = false;
              // this.$message.error("系统错误,请联系管理员!300024");
            });
        } else {
          return false;
        }
      });
    },
    handleClose(status) {
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-form {
  .el-input,
  .el-cascader,
  .el-input-number,
  .el-select {
    width: 100% !important;
  }
  .el-form-item {
    margin-bottom: 0;
  }
}
.suggest {
  z-index: 2;
  position: absolute;
  margin-left: 5px;
  font-size: 12px;
  color: #f56c6c;
}
</style>
